<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">用户登录</h2>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-input-group">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              clearable
              style="width: 200px;"
            />
            <CaptchaImage
              ref="captchaRef"
              :captcha-text="captchaText"
              @update:captcha-text="handleCaptchaUpdate"
            />
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleLogin"
            class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-link type="primary" @click="goToRegister">未注册？去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { login } from '../api/auth'
import { useRouter } from 'vue-router'
import CaptchaImage from '../components/CaptchaImage.vue'

const router = useRouter()
const loginFormRef = ref()
const captchaRef = ref()
const loading = ref(false)
const captchaText = ref('')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.toLowerCase() !== captchaText.value.toLowerCase()) {
          callback(new Error('验证码错误'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 处理验证码更新
const handleCaptchaUpdate = (text: string) => {
  captchaText.value = text
}

// 登录处理函数
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    // 表单验证
    await loginFormRef.value.validate()
    
    loading.value = true
    
    // 验证验证码
    if (loginForm.captcha.toLowerCase() !== captchaText.value.toLowerCase()) {
      ElMessage.error('验证码错误')
      // 刷新验证码
      captchaRef.value?.refreshCaptcha()
      loginForm.captcha = ''
      return
    }
    
    // 调用后端登录API
    const response = await login({
      username: loginForm.username,
      password: loginForm.password
    })
    
    // 处理登录成功
    ElMessage.success('登录成功！')
    
    // 跳转到首页
    router.push('/Home')
    
  } catch (error: any) {
    console.error('登录错误:', error)
    
    if (error.response) {
      // 服务器返回错误
      ElMessage.error(error.response.data.message || '登录失败，请检查用户名和密码')
    } else if (error.request) {
      // 网络错误
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      // 其他错误
      ElMessage.error('登录失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/RegisterView')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.login-form {
  width: 100%;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}
</style> 